package com.uduemc.biso.node.web.component;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import com.uduemc.biso.node.core.entities.SEmail;
import com.uduemc.biso.node.core.property.GlobalProperties;
import com.uduemc.biso.node.web.service.byfeign.EmailService;
import com.uduemc.biso.node.web.utils.EmailUtil;

@Component
public class EmailSendRunner implements ApplicationRunner {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private EmailService emailServiceImpl;

	@Autowired
	private EmailUtil emailUtil;

	@Autowired
	private GlobalProperties globalProperties;

	@Override
	public void run(ApplicationArguments args) {
		int mailThreadPoolsize = globalProperties.getSite().getMailThreadPoolsize();
		for (int i = 0; i < mailThreadPoolsize; i++) {
			emailUtil.startSendMailThread();
		}
		Executors.newSingleThreadScheduledExecutor().schedule(this::loadEmailData, 2, TimeUnit.MINUTES);
		logger.info("初始化完成-----------------------");
	}

	private void loadEmailData() {
		logger.info("加载留存邮件数据----------start-----");
		int start = 0;
		int count = 1000;
		try {
			List<SEmail> emailList;
			do {
				emailList = emailServiceImpl.getEmailList(start, count);
				start += count;
				EmailUtil.addMailQueue(emailList);
			} while (emailList.size() == 1000);
			logger.info("加载留存邮件数据----------end-----");
		} catch (IOException e) {
			logger.error("加载留存邮件数据错误！", e);
		}
	}
}